package com.example.web.filter;

import com.example.web.util.UserUtil;

import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.UUID;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created by liuw on 2017/11/15.
 */
//@Component
//@ServletComponentScan
@Configuration
//@WebFilter(urlPatterns = "/*",filterName = "loginFilter")
public class UserFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        fillUserInfo((HttpServletRequest) request);

        chain.doFilter(request, response);

        clearAllUserInfo();
    }

    private void clearAllUserInfo() {

    }

    private void fillUserInfo(HttpServletRequest request) {
        // 用户信息
        String user = getUserFromSession(request);

        if (user != null) {
            UserUtil.setUser(user);
        }

        // 语言信息
        String locale = getLocaleFromCookies(request);

        if (locale != null) {
            UserUtil.setLocale(locale);
        }
    }

    private String getUserFromSession(HttpServletRequest request) {
        HttpSession session = request.getSession(true);

        //TODO 仅调试使用
        if (session != null) {
            return UUID.randomUUID().toString();
        }

        // 从session中获取用户信息放到工具类中
        return (String) session.getAttribute(UserUtil.KEY_USER);
    }

    private String getLocaleFromCookies(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();

        if (cookies == null) {
            return null;
        }

        for (int i = 0; i < cookies.length; i++) {
            if (UserUtil.KEY_LANG.equals(cookies[i].getName())) {
                return cookies[i].getValue();
            }
        }

        return null;
    }

    @Override
    public void destroy() {

    }
}
